package com.sky.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.function.Consumer;

public interface BaseData {

    default <V> V convertToObject(Class<V> clazz) {
        try {
            // 获取目标类所有字段
            Field[] sourceFields = clazz.getDeclaredFields(); // 所有字段全部取出来
            // 获取目标类的构造器
            Constructor<V> constructor = clazz.getConstructor();
            // 使用目标类构造器创建目标对象
            V targetObject = constructor.newInstance();
            for (Field sourceField : sourceFields) {
                convert(sourceField, targetObject);
            }
            return targetObject;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e.getLocalizedMessage());
        }
    }

    // 使用lambda表达式set值
    default <V> V convertToObject(Class<V> clazz, Consumer<V> consumer) {
        V targetField = this.convertToObject(clazz);
        consumer.accept(targetField);
        return targetField;
    }

    private void convert(Field sourceField, Object targetObject) {
        try {
            // 为了复制字段值，获取当前类中与源字段同名的字段
            Field targetField = this.getClass().getDeclaredField(sourceField.getName());
            // 设置sourceField为可访问
            sourceField.setAccessible(true);
            // 设置targetField为可访问
            targetField.setAccessible(true);

            // 获取当前对象中字段的值
            Object value = targetField.get(this);

            // 检查值不为null再进行设置
            if (value != null) {
                try {
                    // 将当前对象字段的值设置到目标对象的字段中
                    sourceField.set(targetObject, value);
                } catch (IllegalArgumentException e) {
                    // 如果直接设置失败，尝试处理基本类型和包装类型的情况
                    if (value instanceof Number && Number.class.isAssignableFrom(sourceField.getType())) {
                        // 处理数字类型转换
                        Number numValue = (Number) value;
                        if (sourceField.getType() == Long.class || sourceField.getType() == long.class) {
                            sourceField.set(targetObject, numValue.longValue());
                        } else if (sourceField.getType() == Integer.class || sourceField.getType() == int.class) {
                            sourceField.set(targetObject, numValue.intValue());
                        } else if (sourceField.getType() == Double.class || sourceField.getType() == double.class) {
                            sourceField.set(targetObject, numValue.doubleValue());
                        } else if (sourceField.getType() == Float.class || sourceField.getType() == float.class) {
                            sourceField.set(targetObject, numValue.floatValue());
                        }
                    }
                }
            }
        } catch (IllegalAccessException | NoSuchFieldException ignored) {
            // 捕获并忽略IllegalAccessException和NoSuchFieldException异常
        }
    }
}